<?php
class FckModel extends CommonModel {
    //数据库名称

   public function xiangJiao($Pid=0,$DanShu=1){
        //========================================== 往上统计单数
        $where = array();
        $where['id'] = $Pid;
        $field = 'treeplace,father_id';
        $vo = $this ->where($where)->field($field)->find();
        if ($vo){
            $Fid = $vo['father_id'];
            $TPe = $vo['treeplace'];
            $table = $this->tablePrefix.'fck';
            if ($TPe == 0 && $Fid > 0){
                $this->execute("update ". $table ." Set `l`=l+$DanShu, `shangqi_l`=shangqi_l+$DanShu  where `id`=".$Fid);
            }elseif($TPe == 1 && $Fid > 0){
                $this->execute("update ". $table ." Set `r`=r+$DanShu, `shangqi_r`=shangqi_r+$DanShu  where `id`=".$Fid);
            }elseif($TPe == 2 && $Fid > 0){
                $this->execute("update ". $table ." Set `lr`=lr+$DanShu, `shangqi_lr`=shangqi_lr+$DanShu  where `id`=".$Fid);
            }
            if ($Fid > 0) $this->xiangJiao($Fid,$DanShu);
        }
        unset($where,$field,$vo);
    }
    
    public function addencAdd($ID=0,$inUserID=0,$money=0,$num=0,$bz="",$moneytype=0,$l_time=0){
        $time = time();
        if($l_time>0){
            $time=$l_time;
        }
        $where = array();
        $where['id'] = $ID;
        $frs = $this->where($where)->field('id,user_id')->find();
        $where = array();
        $where['id'] = $inUserID;
        $frs2 = $this->where($where)->field('id,user_id')->find();
        $data = array();
        $history = M ('history');
        $data['user_id']        = $frs['user_id'];//获奖会员
        $data['uid']            = $frs['id'];//获奖会员
        $data['action_type']    = $num;
        $data['pdt']            = $time;
        $data['epoints']        = $money;
        $data['bz']             = $bz;
        $data['did']            = $frs2['id'];//来源会员
        $data['user_did']       = $frs2['user_id'];//来源会员
        $data['type']           = 1;
        $data['allp']           = 0;
        $data['moneytype']      = $moneytype;

        $result=$history->add($data);
        unset($data,$history);
    }

    //计算奖金
    public function getusjj($uid,$type=0){
        $mrs = $this->where('id='.$uid)->find();
        if($type!=0){
            if($mrs){
                $this->xiaofeijiang($mrs['user_id'],$type,$mrs['re_path'],$mrs['re_level']);
                $this->lingdaoo($mrs['user_id'],$type,$mrs['p_path']);
            }
            unset($mrs); 
        }else{
            M('fck')->where('id=1')->setInc('chuju',$mrs['cpzj']); // 开通增加公司总业绩
            if($mrs){
                $this->xiaofeijiang($mrs['user_id'],$mrs['cpzj'],$mrs['re_path'],$mrs['re_level']);
                $this->lingdaoo($mrs['user_id'],$mrs['cpzj'],$mrs['p_path']);
            }
            unset($mrs); 
        }
    }
    //求差计算
    public function ZuiDaShouYi($money_a=0,$miney_b=0,$money_c=0,$id=0){
        $moeny = 0;
        $count = $money_a+$money_b;
        if($money_c<$count){
            $moeny = $money_c-$miney_b;
            
        }else{
            $moeny = $money_a;
        }
        if($money_c<=$count){
            $this->where("id='".$id."'")->save(array("is_fenh"=>1,"is_pay"=>0));//静态收益达到两倍停止获得收益
        }
        return $moeny;
    }
 
    //理财收益
    public function liCaiShouYi($id=0,$money=0,$num=0,$NowDate=0,$EndDate=0){
       return false;
        $frs = $this->where("id=".$id)->find();
        $max_sy = $frs['cpzj']*2;//奖金的2倍
        if($frs && $frs['is_fenh']<1){
            $money_count = $this->ZuiDaShouYi($money,$frs["b1"],$max_sy,$frs['id']);
            $myid = $frs['id'];
            $inUserID = $frs['id'];
            if($max_sy > $frs["b1"]){
            $this->rw_bonus($myid,$inUserID,1,$money_count,'理财收益',0,$NowDate,$EndDate);
            }
            //直推奖
            $this->Recommend($frs["id"],$frs["re_id"],$money_count,$NowDate,$EndDate);
            //代理收
            $this->AgencyIncome($frs["id"],$num,$NowDate,$EndDate);
        }
    }
    //直推奖
    public function Recommend($id=0,$re_id=0,$money=0,$NowDate=0,$EndDate=0){
       return false;
        $fee = M('fee');
        $fee_rs = $fee->where("id=1")->field("s4")->find();
        $s4  = bcmul(($fee_rs['s4']/100),$money,2);//直推奖

        $frs = $this->where("id='".$id."'")->find();
        $res = $this->where("id='".$re_id."'")->find();
        $max_sy = $frs['cpzj']*2;//奖金的2倍

        if($frs['re_id']==$re_id && $res['is_fenh']<1){
            
            if($max_sy > $frs["b1"]){
                $this->rw_bonus($re_id,$frs['id'],2,$s4,'直推奖',0,$NowDate,$EndDate);
            }
            //管理奖
            $this->Management($re_id,$id,$s4,$NowDate,$EndDate);
        }
    }
    //管理奖
    public function Management($id=0,$frs_id=0,$money=0,$NowDate=0,$EndDate=0){
       return false;
        $fee = M('fee');
        $fee_rs = $fee->where("id=1")->field("s5,s15")->find();
        $s15 = $fee_rs['s15'];
        $s5  = explode("|",$fee_rs['s5']);//会员级别管理奖百分比
        $frs = $this->where("id='".$id."'")->field("id,user_id,re_path")->find();
        
        if($frs){
            $frs_lis = $this->where("id in (0".$frs['re_path']."0)")->field('id,user_id,u_level')->limit($s15)->field("id,user_id,re_path,u_level,cpzj,is_fenh")->order("id desc")->select();
            foreach($frs_lis as $ke => $val){
                    $max_sy = 0;
                    $sprice = 0;
                    $str5   = 0;
                    $str5   = $s5[$val['u_level']-1]/100;
                    $sprice = bcmul($money,$str5,2);
                    $money  = $sprice;
                    $max_sy = $val['cpzj']*2;//奖金的2倍
                    if($sprice>0 && $val['b1']<$max_sy && $val['is_fenh']<1){
                        $this->rw_bonus($val['id'],$frs_id,3,$sprice,'管理奖',0,$NowDate,$EndDate); 
                    }
            }
        }
    }
    //代理收益
    public function AgencyIncome($id=0,$str16=0,$NowDate=0,$EndDate=0){
       return false;
        set_time_limit(0);
        ini_set('memory_limit','1G');
        $fee = M('fee');
        $fee_rs = $fee->where("id=1")->field("s2,s9")->find();
        // $s2  = explode("|",$fee_rs['s2']);//会员投资金额
        $s9  = explode("|",$fee_rs['s9']);//代理奖金
        $frs = $this->where("id='".$id."'")->field("id,user_id,re_path")->find();
        if($frs){
            $frs_lis = $this->where("id in (0".$frs['re_path']."0) and is_agent>0 and b1<(cpzj*2)")->field('id,user_id,is_agent,u_level,is_fenh')->order("id desc")->select();
            $level = 0;
            $money_lev = 0;
        while(list($key,$value) = each($frs_lis)){
            if($level<$value['is_agent'] ){
                $str9 = 0;
                $str9 = $s9[$value['is_agent']-1]-$money_lev;//每手级差奖金
                $sprice = bcmul($str16,$str9,2);
                if($value['is_fenh']<1){
                    $this->rw_bonus($value['id'],$frs['id'],4,$sprice,'代理收益',0,$NowDate,$EndDate);
                }
                $money_lev = $s9[$value['is_agent']-1];//记录当前每手奖金
                $level = $value['is_agent'];//记录当前代理级别
            }else{
                break;
            }
        }
        // foreach($frs_lis as $key=>$value){
        //     if($level<$value['is_agent']){
        //         $str9 = 0;
        //         $str9 = $s9[$value['is_agent']-1]-$money_lev;//每手级差奖金
        //         $sprice = bcmul($str2,$str9,2);
        //         $this->rw_bonus($value['id'],$frs['id'],4,$sprice,'代理收益');
        //         $money_lev = $s9[$value['is_agent']-1];//记录当前每手奖金
        //         $level = $value['is_agent'];//记录当前代理级别
        //     }
        // }
        }
    }
    //升级代理
    public function UpgradeAgent($id=0){
       return false;
        $fee = M('fee');
        $fee_rs = $fee->where("id=1")->field("s6,s7,s8")->find();
        $s7  = explode("|",$fee_rs['s7']);
        $s8  = explode("|",$fee_rs['s8']);
        $frs = $this->where("id='".$id."'")->find();
        $last = count(explode("|",$fee_rs['s6']));//最后一个级别
        $shoplx = 0;
        if($frs && $frs['is_fenh']<1){
            $frs_lis = $this->where("id in (0".$frs['re_path']."0) and is_agent<".$last)->field("id,zjj,re_path,is_agent,u_level")->order("id desc")->select();
            foreach($frs_lis as $value){
                $bonus = 0;
                $i = 0;
                $shoplx = 0;
                $bonus = $this->where("re_path like ('%".$value['id']."%')")->sum("zjj");
                foreach ($s8 as $key=>$val){
                $i = $key+1;//代理级别
                    if($val<=$bonus && $s7[$key]<=$value['u_level']){
                        $shoplx = $i;
                    }
                }
                if($shoplx>0){
                    $this->where("id='".$value['id']."'")->save(array("shoplx"=>$shoplx));
                    // $this->addencAdd($value['id'],$value['id'],0,9,'代理升级','agent_use');
                }
            }
        }
    }
    //商城奖金
    // public function ShopBonus($id=0,){
    //     $fee = M('fee');
    //     $fee_rs = $fee->where("id=1")->field("s12,s13")->find();
    //     $s12 = $fee_rs['s12']/100;//商城奖金百分比
    //     $s13 = $fee_rs['s13'];//动态收益+代理奖
    //     $frs = $this->where("id='".$id."' and is_agent>0")->find();
    //     if($frs['agent_cf']>=$s13){
    //        $sprice = bcmul($s12,$money);
    //        $this->rw_bonus($frs['id'],$frs['id'],6,$sprice,'代理收益');
    //     }
    // }
//董事日分红
    public function quanqiu(){
        $fee_rs = M('fee')->field('s16,s19')->find();
        $s16 = explode('|', $fee_rs['s16']);
        $s19 = explode('|', $fee_rs['s19']);
        $i7 = M('fck')->where('id=1')->find();//公司总业绩
        $i7 = $i7['chuju'];
        $fes = array_combine($s16,$s19);
        $time = strtotime(date('Y-m-d',time()));//时间戳整点
        $yixing = $s16[0]*10000;//一星董事
        $feng = M('fck')->where('zjj>='.$yixing.' and day_feng!='.$time)->order('zjj desc')->select();
        foreach ($feng as $key => $value) {
            foreach ($fes as $key2 => $value2) {
                if($value['zjj']>=$key2*10000){
                    $bai = $value2/100;
                }
            }
            $money = $i7*$bai;
            if($money>0){
            A('Common')->zijin_log($value['id'],$value['user_id'],"month","董事分红",$money,"agent_use");
            }
            M('fck')-> where('id='.$value['id'])->setField('day_feng',$time);//保存分红时间
        }
        

    }

    public function lingdaoo($user_id,$cpzj,$p_path){
       return false;
        $fee_rs = M('fee')->find();
        $s7 = explode('|', $fee_rs['s7']);//领导津贴
        $s12 = explode('|', $fee_rs['s12']);
        $s5 = $fee_rs['s5'];//最小业绩
        //领导津贴
        $zjj = M('fck')->where('id in(0'.$p_path.'0) and is_pay>0 and is_bb>0')->order('id desc')->select();
        $mus = 0;
        foreach ($zjj as $kk => $vv) {
            $isbb = $vv['is_bb']-1;
            $money = $cpzj*($s7[$isbb]-$mus)/100;
            if($money == 0){
                $money = $cpzj/100;
            }elseif ($money < 0) {
                $money = 0;
            }
            if($money>0){
                
             A('Common')->zijin_log($vv['id'],$vv['user_id'],"month","会员{$user_id}的领导津贴",$money,"agent_use");
             $mus = $isbb+2;
            }
        }

        $zjj = M('fck')->where('id in(0'.$p_path.'0) and is_pay>0')->order('p_level desc')->select();
        //增加总业绩+升级
        foreach ($zjj as $key => $value) {
            if($value['is_bb']<1){
           
                //查询团队业绩
                $l = M('fck')->where('father_id='.$value['id'].' and treeplace=0')->field('cpzj,zjj')->find();//左区
                $l = $l['cpzj']+$l['zjj'];
                $r = M('fck')->where('father_id='.$value['id'].' and treeplace=1')->field('cpzj,zjj')->find();//右区
                $r = $r['cpzj']+$r['zjj'];
                $lr = M('fck')->where('father_id='.$value['id'].' and treeplace=2')->field('cpzj,zjj')->find();//三区
                $lr = $lr['cpzj']+$lr['zjj'];
                $array=array($l,$r,$lr);
                 rsort($array);
                $min = min($array[0],$array[1]);//三区第二小业绩                      
                $yeji = $s12[0]*10000;
                if($value['zjj']>=$yeji && $min>=$s5){
                    $data['is_bb'] = 1;
                    M('fck')->where('id='.$value['id'])->save($data);
                }//领导升级（主任）

             }else{
                 //查询团队业绩
                $l = M('fck')->where('father_id='.$value['id'].' and treeplace=0')->field('id')->find();//左区
                $l = M('fck')->where('p_path like "%'.$l['id'].'%" or id='.$l['id'])->field('is_bb')->order('is_bb desc')->find();//左区团队最小级别

                $r = M('fck')->where('father_id='.$value['id'].' and treeplace=1')->field('id')->find();//右区
                $r = M('fck')->where('p_path like "%'.$r['id'].'%" or id='.$r['id'])->field('is_bb')->order('is_bb desc')->find();
                $lr = M('fck')->where('father_id='.$value['id'].' and treeplace=2')->field('id')->find();//三区
                $lr = M('fck')->where('p_path like "%'.$lr['id'].'%" or id='.$lr['id'])->field('is_bb')->order('is_bb desc')->find();
                $array=array($l,$r,$lr);
                 rsort($array);
                 if($array[1]['is_bb']>=$value['is_bb']){
                    $yeji = $value['is_bb']*10000;
                    if($value['zjj']>=$yeji){
                        $data['is_bb'] = $value['is_bb']+1;
                        if($data['is_bb']>8){
                            $data['is_bb'] = 8;
                        }
                        M('fck')->where('id='.$value['id'])->save($data);
                    }

                 }
             }
             
        }
       

    }

public function aaa(){
    set_time_limit(0);
    //事务开始
    //  在User模型中启动事务
            M()->startTrans();
            // 进行相关的业务逻辑操作
  $a = $this->execute("update __TABLE__ set a=a+1 where id=1");
  $b = true;
            if ($a and $b){
                // 提交事务
                M()->commit(); 
            }else{
               // 事务回滚
               M()->rollback(); 
            }
}

   public function xiaofeijiang($user_id,$cpzj,$p_path,$p_level){  
        $fee_rs = M('fee')->find();
        $s6 = explode('|', $fee_rs['s6']);//互助银卡
        $s4 = explode('|', $fee_rs['s4']);//互助金卡
        $s14 = explode('|', $fee_rs['s14']);//互助铂金卡
        $s13 = explode('|', $fee_rs['s13']);//互助钻石卡
        $s15 = explode('|', $fee_rs['s15']);//累计金额
        $p_path = M('fck')->where('id in(0'.$p_path.'0) and is_pay>0')->field('id,re_level,u_level,pdt,user_id')->limit(12)->order('id desc')->select();
        foreach ($p_path as $key => $value) {
            $pleve = $p_level-$value['re_level'];//极差
            $pl = $pleve-1;
            if($value['u_level']>3){
                //钻石卡
                $money = $s13[$pl]/100*$cpzj;
            }elseif($value['u_level']>2){
                $money = $s14[$pl]/100*$cpzj;
                //铂金卡
            }elseif($value['u_level']>1){
                $money = $s4[$pl]/100*$cpzj;
                //金卡
            }else{
                //银卡
                    $money = $s6[$pl]/100*$cpzj;
            }
            if($money>0){
                
            A('Common')->zijin_log($value['id'],$value['user_id'],"month","会员{$user_id}的消费奖励",$money,"agent_use");
            }
            $str1 = explode('|', $fee_rs['str1']);//前面人数
            $s3 = explode('|', $fee_rs['s3']);//后面人数
            //团队互助
             $qian = M('fck')->where('pdt <'.$value['pdt'].' and is_pay>0')->field('id,user_id,u_level')->limit(20)->order('id desc')->select();      
             $pai = 0;
             foreach ($qian as $key2 => $value2) {
                 $pai = $pai+1;//相差人数
                 $ule = $value2['u_level']-1;//人数键值
                    if($pai <= $str1[$ule]){
                        $money_count = $money*0.005;
                        if($money_count>0){
                            A('Common')->zijin_log($value2['id'],$value2['user_id'],"month","会员{$value['user_id']}的团队互助奖励",$money_count,"agent_use");
                                //自助升级
                                $this->jijin($value2['id'],$money_count);
                        }
                    }
                 $money_count = 0;
             }
             $hou = M('fck')->where('pdt >'.$value['pdt'].' and is_pay>0')->field('id,user_id,u_level')->limit(20)->order('id')->select();
             $pai = 0;
             foreach ($hou as $key3 => $value3) {
                  $pai = $pai+1;//相差人数
                 $ule = $value3['u_level']-1;//人数键值
                 if($pai <= $s3[$ule]){
                    $money_counts = $money*0.005;
                    if($money_counts>0){
                        A('Common')->zijin_log($value3['id'],$value3['user_id'],"month","会员{$value['user_id']}的团队互助奖励",$money_counts,"agent_use");
                        $this->jijin($value3['id'],$money_counts);//累计升级
                    }
                 }

                 $money_counts = 0;
             }

              $money = 0;

        }
   }
    
    public function jijin($id,$money_count){
        $fee_rs = M('fee')->find();
        $s15 = explode('|', $fee_rs['s15']);//累计金额
        $value2 = M('fck')->where('id='.$id)->find();     
        $cen = $value2['p_level'];
        if($value2['leiji']+$money_count>=$s15[$value2['benqi_l']]){
            $ji = $value2['benqi_l']+1;
               //算钱
                $money_count2 = $s15[$value2['benqi_l']]*0.5;
                if($money_count2>0){
                    //节点人
                    $re = $this->where('id='.$value2['father_id'].' and benqi_l>='.$ji)->field('id,user_id')->find();
                    A('Common')->zijin_log($re['id'],$re['user_id'],"month","升级基金奖励",$money_count2,"agent_use"); 

                    $da['leiji'] = $value2['leiji']+$money_count-$s15[$value2['benqi_l']];//累计金额
                    if($ji>18){
                        $da['benqi_l'] = 0;
                    }else{
                        $da['benqi_l'] = $ji;
                    }
                    M('fck')->where('id='.$value2['id'])->save($da);
                }                                                     
        }else{
            $da['leiji'] = $value2['leiji']+$money_count;//累计金额
            M('fck')->where('id='.$value2['id'])->save($da);
        }
    }
   
    //各种扣税
    public function rw_bonus($myid,$inUserID=0,$bnum=0,$money=0,$bz=0,$time=0,$NowDate=0,$EndDate=0){
       /*if(!($bnum==2 || $bnum==3 || $bnum==4)) {
           return false;
       }*/
       if($money < 0 ) return false;

       //判断消费金额达到没有是否可以获取奖励
        //if (!$this->gouwuIsGetPrice($myid))  return false;

        $fee = M('fee');
        $fee_rs = $fee->field('s10,s12,s13')->find();

        $s10 = bcmul(($fee_rs['s10']/100),$money,2);//慈善基金
        $s12 = $fee_rs['s12']/100;//商城奖金百分比
        $s13 = $fee_rs['s13'];//动态收益+代理奖

        $s10 = 0;
        $s12 = 0;
        $s13 = 0;

        $money_a = 0;
        $money_v = 0;//商城奖金
        $money_n = 0;//动态收益+代理奖
        $last_m = $money-$s10;//余额
        $last_m = $money;
            
        /*$frs = $this->where("id='".$myid."' and is_agent>0")->find();
        if($frs['agent_kt']>$s13){
           $money_v = bcmul($s12,$money);//商城奖金
           $last_m  = $last_m-$money_v;
        }*/

        if($bnum!=1){
            $money_n = $last_m;//所有动态奖+代理奖
        }else{
            $money_a = $last_m;//静态收益
        }
        $bonus = M('bonus');
        $bid = $this->_getTimeTableList($myid,$NowDate,$EndDate);
        $inbb = "b".$bnum;
        //$bonus->execute("UPDATE __TABLE__ SET b0=b0+".$last_m.",".$inbb."=".$inbb."+".$last_m.",b5=b5+".$s10.",b6=b6+".$money_v."  WHERE id={$bid}"); //加到记录表
        $b_rs = $bonus->execute("UPDATE __TABLE__ SET b0=b0+".$last_m.",".$inbb."=".$inbb."+".$last_m."  WHERE id={$bid}"); //加到记录表

        $this->execute("UPDATE __TABLE__ SET agent_use=agent_use+".$last_m.",zjj=zjj+".$last_m.",agent_kt=agent_kt+".$money_n.",agent_cf=agent_cf+".$money_v.",b1=b1+".$money_a." where id=".$myid);

        unset($bonus);
        $time=$EndDate;
        if($last_m>0){
            $this->addencAdd($myid,$inUserID,$last_m,$bnum,$bz,'agent_use',$time);
        }

        /*if($s10>0){
            $this->addencAdd($myid,$inUserID,-$s10,5,'慈善基金','agent_use',$time);
        }
        if($money_v>0){
            $this->addencAdd($myid,$inUserID,$money_v,6,'商城奖金','agent_cf',$time);
        }*/
        unset($fee,$fee_rs);
    }

    private function gouwuIsGetPrice($id) {
       $limit_price = $this->getFeeRule(['min_get_price'])['min_get_price'];
       $gouwu = M('gouwu')->where(['have_pay' => 1, 'uid' => $id])->field('sum(cprice)')->group('uid')->having("sum(cprice) >= $limit_price")->find();
       return (empty($gouwu) || !$gouwu) ? false : true;
    }

    public  function _getTimeTableList($uid=0,$NowDate=0,$EndDate=0){
        $times = M ('times');
        $bonus = M ('bonus');
        $boid = 0;
        // $nowdate = strtotime(date('Y-m-d'))-1;
        $benqi = strtotime(date('Y-m-d'))-1+3600*24;
        $shangqi = strtotime(date('Y-m-d'));
        if($NowDate>0 || $EndDate>0){
            $shangqi = $NowDate;
            $benqi   = $EndDate-1+3600*24;
        }
        
        $settime_two['benqi'] = $benqi;
        $settime_two['type']  = 0;
        $trs = $times->where($settime_two)->find();
        if(!$trs){
            // $rs3 = $times->where('type=0')->order('id desc')->find();
            // if($rs3){
            //     $data['shangqi']  = $rs3['benqi'];
            //     $data['benqi']    = $benqi;
            //     $data['is_count'] = 0;
            //     $data['type']     = 0;
            // }else{
                $data['shangqi']  = $shangqi;
                $data['benqi']    = $benqi;
                $data['is_count'] = 0;
                $data['type']     = 0;
            // }
            
            // unset($rs3);
            $boid = $times->add($data);
            unset($data);
        }else{
            $shangqi = $trs['shangqi'];
            $benqi   = $trs['benqi'];
            $boid = $trs['id'];
        }

        $_SESSION['BONUSDID'] = $boid;
        $brs = $bonus->where("uid={$uid} AND did={$boid}")->find();
        if($brs){
            $bid = $brs['id'];
        }else{
            $frs = $this->where("id={$uid}")->field('id,user_id')->find();
            $data = array();
            $data['did'] = $boid;
            $data['uid'] = $frs['id'];
            $data['user_id'] = $frs['user_id'];
            $data['e_date'] = $benqi;
            $data['s_date'] = $shangqi;
            $bid = $bonus->add($data);
        }
        return $bid;
    }


    /**
     * 购物消费 发放奖金
     * @param $all_id
     * @param int $base_money
     */
    public function priceComm($gid, $base_money=0) {
        $fee = $this->getFeeRule();
        $where['g.id'] = $gid;
        $rs = M('gouwu')
            ->alias('g')
            ->field('g.cprice,f.*')
            ->join('xt_fck AS f ON g.uid=f.id')
            ->where($where)
            ->find();

        if($rs['cprice'] < $fee['min_get_price']) return false;
        //if($rs['cprice'] < $fee['min_get_price']  && !$this->gouwuIsGetPrice($rs['id'])) return false;

        //$this->priceTeamRe($rs, $fee, $rs['cprice']);    //团队奖
        $this->priceService($rs, $fee, $rs['cprice']);    //服务奖
        $this->priceManageMonth($rs, $fee, $rs['cprice']);
    }

    /**
     * 1) 开通分享奖
     * @param $shoplx
     * @param $id_to_open
     */
    public function priceOpen($id_to_open, $shoplx=0) {
        return false;   //停止发奖
        /*if($shoplx == 1) {   //分享市级中心发奖
            $this->priceCityOpen($id_to_open);
        } else if($shoplx == 2) {    //分享体验中心发奖
            $this->priceExperienceOpen($id_to_open);
        } else if ($shoplx == 0) {
            $this->priceMemberOpen($id_to_open);
        }*/
    }

    /**
     * 直推奖发放,复消奖 不用要
     * @param $id 获奖用户ID
     * @param $user_id 引发奖项的用户user_id
     */
    private function priceShop($rs, $ratio, $base_money){
        $gouwu = M('gouwu')->where(['uid' => $rs['id'], 'have_pay' => 1])->order('okdt desc')->limit(2)->count();
        $bz_name = '';
        $bnum = 0;

        //if(!$gouwu || empty($gouwu)) {
        if($gouwu && $gouwu == 1) {
            /*$ratio = $ratio['s4'];
            $bz_name = '推荐奖';
            $bnum = 1;*/
            return false;
        } else {
            $ratio = $ratio['s5'];  //重复消费
            $bz_name = '复消奖';
            $bnum = 2;
        }

        if ( ($price = bcmul($base_money, $ratio/100, 2)) <= 0) return false;

        $where['id'] = $rs['re_id'];
        $where['is_fenh'] = 0;
        $where['is_pay'] = 1;
        $frs = $this->where($where)->field('id,user_id')->find();
        if(!$frs || empty($frs))  return false;

        $this->rw_bonus($rs['re_id'], $rs['id'],$bnum, $price, $bz_name);
        unset($rs);
    }


    /**
     * 分享会员开通奖
     */
    private function priceMemberOpen($by_id) {

        $fee = $this->getFeeRule();
        $child_rs = $this->where(['id' => $by_id])->find();
        $rs = $this->where(['id' => $child_rs['re_id'], 'is_pay' => 1])->find();

        if($rs['is_agent'] == 2 && $rs['shoplx'] == 1) {    //市级中心
            $ratio = $fee['city_price_ratio'][0];
            $bz_name = '分享会员开通';

        } else if($rs['is_agent'] == 2 && $rs['shoplx'] == 2) {     //体验中心
            $ratio = $fee['experience_price_ratio'][0];
            $bz_name = '分享会员开通';
        } else {    //会员
            $ratio = $fee['member_price_ratio'][0];
            $bz_name = '分享会员开通';
        }

        $bnum = 4;
        $price = bcmul($child_rs['cpzj'], $ratio/100, 2);

        $this->rw_bonus($rs['id'], $by_id, $bnum, $price, $bz_name);
    }

    /**
     * 分享体验中心开通
     * @param $by_id
     */
    private function priceExperienceOpen($by_id) {
        $fee = $this->getFeeRule();
        $child_rs = $this->where(['id' => $by_id])->find();
        $fa_rs = $this->where(['id' => $child_rs['re_id'], 'is_pay' => 1])->find();

        $bz_name = '分享体验中心';
        if($fa_rs['is_agent'] == 2 && $fa_rs['shoplx'] == 1) {    //市级中心
            $ratio = $fee['city_price_ratio'][1];

        } else if($fa_rs['is_agent'] == 2 && $fa_rs['shoplx'] == 2) {     //体验中心
            $ratio = $fee['experience_price_ratio'][1];

        } else {    //会员
            $ratio = $fee['member_price_ratio'][1];

        }

        $bnum = 5;
        $price = bcmul($child_rs['cpzj'], $ratio/100, 2);

        $this->rw_bonus($fa_rs['id'], $by_id, $bnum, $price, $bz_name);
    }

    /**
     * 分享城市中心开通
     * @param $by_id
     */
    private function priceCityOpen($by_id) {
        $fee = $this->getFeeRule();
        $child_rs = $this->where(['id' => $by_id])->find();
        $fa_rs = $this->where(['id' => $child_rs['re_id'], 'is_pay' => 1])->find();
        if(!$fa_rs) return false;

        $bz_name = '分享市级开通';
        if($fa_rs['is_agent'] == 2 && $fa_rs['shoplx'] == 1) {    //市级中心
            $ratio = $fee['city_price_ratio'][2];

        } else if($fa_rs['is_agent'] == 2 && $fa_rs['shoplx'] == 2) {     //体验中心
            $ratio = $fee['experience_price_ratio'][2];

        }

        $bnum = 6;
        $price = bcmul($child_rs['cpzj'], $ratio/100, 2);
        $this->rw_bonus($fa_rs['id'], $by_id, $bnum, $price, $bz_name);
    }

    /**
     * 团队奖，推荐关系
     * @param $id 获奖用户ID
     * @param $user_id 引发奖项的用户user_id
     */
    private function priceTeamRe($rs, $fee, $base_money){
        $re_level_lim = 2;
        $all_re_father = $this->where("is_pay = 1 and id in (0{$rs['re_path']}0) and {$rs['re_level']} - re_level <= {$re_level_lim}")->order('re_level desc')->select();
        $bnum = 7;
        foreach ($all_re_father as $re) {
            $ratio = 0;
            $level = $rs['re_level'] - $re['re_level'];
            if($re['is_agent'] == 0  && $level <= 1) {   //判断父点,正式会员
                $ratio = isset($fee['team_mem']) ? $fee['team_mem'] : $fee['team_mem'][0];
                $bz_name = '团队奖-正式会员 -' . $level . '代';
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 2) {   //判断体验中心
                $ratio = $fee['team_experience'][$level - 1];    //根据代数获取比率
                $bz_name = '团队奖-体验中心 - '. $level . '代';
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 1) {     //市级中心
                $ratio = $fee['team_city'][$level - 1];    //根据代数获取比率
                $bz_name = '团队奖-市级中心 - ' . $level . '代';
            }

            if ($ratio == 0 || ($price = bcmul($base_money, $ratio/100, 2)) <= 0 ) continue;


            //$this->award_bonus($rs['re_id'], $rs['user_id'], $type, $price);
            $this->rw_bonus($re['id'], $rs['id'],$bnum, $price, $bz_name);
        }

        unset($rs,$all_re_father);
    }

    /**
     * 服务奖，推荐关系
     * @param $id 获奖用户ID
     * @param $user_id 引发奖项的用户user_id
     */
    private function priceService($rs, $fee, $base_money, $bnum = 2){
        $re_level_lim = 2;
        $all_re_father = $this->where("is_pay = 1 and id in (0{$rs['re_path']}0)")->order('re_level desc')->select();

        foreach ($all_re_father as $re) {
            $ratio = 0;
            $level = $rs['re_level'] - $re['re_level'];
            if($re['is_agent'] == 0  && $level <= 1) {   //判断父点,正式会员
                //会员不拿
                /*$ratio = isset($fee['team_mem']) ? $fee['team_mem'] : $fee['team_mem'][0];
                $bz_name = '服务奖-正式会员 -' . $level . '代';*/
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 2 && $re['re_level'] != $rs['re_level']) {   //判断体验中心,同级不拿
                $ratio = $fee['s5'][0];    //根据代数获取比率
                $bz_name = '服务奖-体验中心';
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 1) {     //市级中心
                $ratio = $fee['s5'][1];    //根据代数获取比率
                $bz_name = '服务奖-市级中心';
            }

            if ($ratio == 0 || ($price = bcmul($base_money, $ratio/100, 2)) <= 0 ) continue;

            $this->rw_bonus($re['id'], $rs['id'],$bnum, $price, $bz_name);
        }


        if(!$rs['f_agent_city'] || $rs['shoplx'] != 2) return false;  //没有上级城市

        //区域内体验中心团队，查找不在推荐链上的
        $service_rs  = $this->where("is_pay = 1 and is_agent = 2 and shoplx = 1 and id not in (0{$rs['re_path']}0) 
                                and (shop_b = '{$rs['f_agent_city']}'  OR shop_a = '{$rs['f_agent_city']}'  OR 
                                      shop_b like '{$rs['f_agent_city']}%' OR shop_a like '{$rs['f_agent_city']}%')")
                            ->field('id,user_id,shop_a,shop_b,shop_c,is_agent')
                            ->find();


        $ratio = $fee['s5'][1];    //根据代数获取比率
        $bz_name = '服务奖-区域内-市级中心';

        if ($ratio == 0 || ($price = bcmul($base_money, $ratio/100, 2)) <= 0 ) return false;
        $this->rw_bonus($service_rs['id'], $rs['id'],$bnum, $price, $bz_name);

        unset($rs,$all_re_father);
    }


    /**
     * 管理奖，月结
     * @param $id 获奖用户ID
     * @param $user_id 引发奖项的用户user_id
     */
    private function priceManageMonth($rs, $fee, $base_money, $bnum = 3){
        $re_level_lim = 2;
        $all_re_father = $this->where("is_pay = 1 and id in (0{$rs['re_path']}0) and {$rs['re_level']} - re_level <= {$re_level_lim}")
                                ->order('re_level desc')
                                ->select();

        foreach ($all_re_father as $re) {
            $ratio = 0;
            $level = $rs['re_level'] - $re['re_level'];
            if($re['is_agent'] == 0  && $level <= 1) {   //判断父点,正式会员
                $ratio = isset($fee['team_mem']) ? $fee['team_mem'] : $fee['team_mem'][0];
                $bz_name = '管理奖-正式会员 -' . $level . '代';
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 2) {   //判断体验中心
                $ratio = $fee['team_experience'][$level - 1];    //根据代数获取比率
                $bz_name = '管理奖奖-体验中心 - '. $level . '代';
            } else if($re['is_agent'] == 2  && $re['shoplx'] == 1) {     //市级中心
                $ratio = $fee['team_city'][$level - 1];    //根据代数获取比率
                $bz_name = '管理奖-市级中心 - ' . $level . '代';
            }

            if ($ratio == 0 || ($price = bcmul($base_money, $ratio/100, 2)) <= 0 ) continue;

            $this->create_manage_price_temp($re, $rs, $bnum, $price, $bz_name);
            //$this->award_bonus($rs['re_id'], $rs['user_id'], $type, $price);
            //$this->rw_bonus($re['id'], $rs['id'],$bnum, $price, $bz_name);
        }

        unset($rs,$all_re_father);
    }

    /**
     * 临时保存管理奖，每月再发奖
     */
    private function create_manage_price_temp($price_user, $in_user, $bnum, $price, $bz_text) {
        $data = [];
        $data['uid']            = $price_user['id'];
        $data['user_id']        = $price_user['user_id'];
        $data['in_uid']          = $in_user['id'];
        $data['in_user_id']     = $in_user['user_id'];
        $data['action_type']    = $bnum;
        $data['epoints']        = $price;
        $data['bz_text']        = $bz_text;
        $data['create']         = time();
        //$data['pdt']            = time();
        $data['save']           = 0;
        $result =M('manage_price_temp')->add($data);

        return $result;
    }


    /**
     * 一线公排，开启奖金
     * @param $id
     * @return bool
     */
    public function priceReturn($id, $bnum = 1) {
        $s12_ratio = $this->getFeeRule(['s12'])['s12'];

        $bz_name = '返现奖';
        $price = $s12_ratio['0'];
        $sub_ratio = $s12_ratio['1'];

        /*if(!$this->gouwuIsGetPrice($id)) return false;*/

        $where['id'] = $id;
        $where['is_fenh'] = 0;  //是否开启奖金
        $where['is_pay'] = 1;  //是否激活用户
        $frs = $this->where($where)->field('id,user_id')->find();
        if(!$frs || empty($frs))  return false;

        $price = bcmul($price, (100 - $sub_ratio)/100, 2);
        $this->rw_bonus($id, $id,$bnum, $price, $bz_name);
    }



    /**
     * 获取全部的fee表或者其中一个,单个不用取下标
     * @param string $ratio_name_s
     * @return array|bool
     */
    public function getFeeRule($ratio_name_s='') {
        $fee = M('Fee')->field($ratio_name_s)->find();
        if(!$fee) return false;

        $rule_single = array();
        $rule_pair = array();
        foreach ($fee as $pair_name => $pair_val) {
            $rule[$pair_name] = explode("|", $pair_val);
            foreach ($rule[$pair_name] as $key=>$val) {
                $item = explode("-", $val);
                if(isset($item[1])) {   //有多个键值
                    $rule_pair[$pair_name][$item[0]] = $item[1];
                } else {    //只有单个值
                    if(count($rule[$pair_name]) == 1) {
                        $rule_single[$pair_name] = $val;
                    } else {
                        $rule_single[$pair_name] = $rule[$pair_name];
                    }
                }
            }
        }

        return array_merge($rule_single, $rule_pair);
    }


    /**
     * 发放奖金，计算判断发放
     * @param $myid 得奖ID
     * @param int $inUserID 操作ID
     * @param int $bnum Fck中的innb，奖的类型
     * @param int $money_count 发放奖金金额
     * @param bool $day_lim     是否每日封顶
     * @param bool $up_time     是否更新每日封顶金额
     */
    public function award_bonus($myid, $inUserID=0, $bnum=0, $money_count=0, $day_lim=false, $up_time=false){
        $ratio_a = $this->getUrRatio($myid,['s6','str4','s5']);
        $s6_repeat = $ratio_a['s6'];    //重消奖 扣费重复消费 比例
        $str4_tax = $ratio_a['str4'];   //进入慈善基金, 个人所得税
        //$s5_game = $ratio_a['s5'];  //10%进人游戏币


        $money_rep = 0;     //重复消费扣费
        $money_stat1 = 0;    //静态分配， 电子币
        $money_tax = 0;     //扣税
        $money_stat2 = 0;   //静态分配， 云通币之类

        //练手三
        /* if($bnum ==1 || $bnum== 6 || $bnum ==11 ||$bnum==13 || $bnum==14) {
             $money_stat1 = $money_count * $s5_game;      //扣除动态收益的10%,进入游戏币
         } else {
             //练手三不需要扣除税费
         }*/

        /*$money_rep = bcmul($money_count, $s6_repeat, 2);     //扣除重复消费
        $money_tax = bcmul($money_count, $str4_tax, 2);   //扣除个人所得税*/

        $money_left = $money_count - $money_rep - $money_tax - $money_stat1 - $money_stat2;    //剩余，此值写入现金账户

        $bid = $this->_getTimeTableList($myid);     //返回 Bonus表中的用户ID, 保存到Bonus,time表中
        $inbb = "b".$bnum;      //奖项的代号 b1,b2...b12

        $usqla = "";
        if($day_lim) {   //判断是否是什么奖， 每日封顶,更新每日封顶
            $usqla = $up_time ? ",day_feng=".$money_count."" : ",day_feng=day_feng+".$money_count."";
            $usqla .= ",update_time=".time()."";
        }
        $usqlc = "agent_use=agent_use+".$money_left.",agent_cash=agent_cash+".$money_stat1.",agent_xf=agent_xf+".$money_stat2;

        $bonus = M('bonus');
        $bonus->execute("UPDATE __TABLE__ SET b0=b0+".$money_left.",b9=b9-".$money_rep.",b10=b10-".$money_tax.",".$inbb."=".$inbb."+".$money_count."  WHERE id={$bid}"); //加到记录表
        $this->execute("update __TABLE__ set ".$usqlc.",zjj=zjj+".$money_count.",xy_money=xy_money+".$money_count.$usqla." where id=".$myid);//加到fck
        unset($bonus);

        //数据金额的保存
        if($money_count>0){
            $this->addencAdd($myid,$inUserID,$money_count,$bnum);
        }
        if($money_left > 0){      //还有剩余金额保存在现金账户
            $this->addencAdd($myid,$inUserID,$money_left,25,0,0,0,"进入现金币账户");
        }
        if($money_stat1>0){    //进入电子币
            $this->addencAdd($myid,$inUserID,$money_stat1,25,0,0,0,"进入游戏电子币账户");
        }
        /*
        if($money_stat2 > 0){    //进入云通币账户
            $this->addencAdd($myid,$inUserID,$money_stat2,25,0,0,0,"进入云通币账户");
        }*/

        if($money_rep > 0){       //扣除重复消费
            $this->addencAdd($myid,$inUserID,-$money_rep,9);
        }
        if($money_tax > 0){    //扣除税
            $this->addencAdd($myid,$inUserID,-$money_tax,10);
        }

        unset($fck_rs);
    }

}
?>